package com.zhao.service.task;

import java.util.concurrent.Future;

import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import com.zhao.data.model.Message;

/**
 * @author zhaoyongfei
 *
 */
@Service
public class AsyncMessageSender {
	protected static final Logger logger = LoggerFactory.getLogger(AsyncMessageSender.class);
	@Autowired
	JavaMailSender javaMailSender;

	@Async
	public Future<String> sendEmail(final Message message) {
		String result = "success";
		try {
			MimeMessage mimeMessage = javaMailSender.createMimeMessage();
			MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
			mimeMessageHelper.setSubject(message.getSubject());
			mimeMessageHelper.setTo(message.getToUser());
			mimeMessageHelper.setFrom(message.getFromUser());
			mimeMessageHelper.setText(message.getText(), true);
			javaMailSender.send(mimeMessage);
			logger.debug("send message {}", "success");
		} catch (Exception e) {
			result = "failture";
			logger.debug("send message {}", e);
			e.printStackTrace();
		}
		return new AsyncResult<String>(result);
	}
}
